import { getUserList } from "@/api/system/user";
import { getIsSuperAdmin } from "@/api/system/user";
import { onMounted, ref, reactive, computed } from "vue";
import { useUserStore } from "@/store/modules/user";

export function useAdminHooks() {
  const userStore = useUserStore();
  const adminList = ref([]);

  // 判断是否为超级管理员
  const isSuperAdmin = ref(false);

  // 检查超级管理员权限
  const checkSuperAdmin = async () => {
    const isSuperAdminRes = await getIsSuperAdmin();
    if (isSuperAdminRes.success) {
      isSuperAdmin.value = isSuperAdminRes.data;
    }
  };

  // 获取当前用户名
  const currentUsername = computed(() => userStore.username);

  const initialForm = {
    search_type: "",
    search_value: "",
    admin_id: "",
    page: 1,
    limit: 100
  };

  const form = reactive({ ...initialForm });

  const getList = async () => {
    const params: Record<string, any> = {
      page: form.page,
      limit: form.limit
    };

    if (form.search_type !== "") {
      form[form.search_type] = form.search_value;
      params[form.search_type] = form.search_value;
    }

    if (form.admin_id) {
      params.admin_id = form.admin_id;
    }

    const response = await getUserList(params);
    adminList.value = response.data.list;
  };

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();

    Object.keys(form).forEach(key => {
      if (!(key in initialForm)) {
        delete form[key];
      }
    });

    Object.assign(form, initialForm);
    getList();
  };

  onMounted(() => {
    getList();
    checkSuperAdmin();
  });

  return {
    adminList,
    form,
    getList,
    resetForm,
    isSuperAdmin,
    currentUsername
  };
}
